package com.fowo.api.common.util;

import lombok.experimental.UtilityClass;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求相关工具
 */
@UtilityClass
public class RequestUtils {

    public HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            return servletRequestAttributes.getRequest();
        }
        return null;
    }

    /**
     * 获取当前请求的来源地址
     */
    public String getRemoteAddr() {
        HttpServletRequest request = getRequest();
        String remoteAddr = request.getRemoteAddr();
        String xForwardedFor = request.getHeader("x-forwarded-for");
        if (StringUtils.hasText(xForwardedFor)) {
            return xForwardedFor;
        }
        return remoteAddr;
    }

    /**
     * 获取当前请求的 User-Agent 头
     */
    public String getUserAgent() {
        HttpServletRequest request = getRequest();
        return request.getHeader("User-Agent");
    }
}
